package com.wushi.lenovo.asia5b.app_utils.status_bar_util;

import android.app.Activity;
import android.content.Context;
import android.os.Build;
import android.support.annotation.ColorInt;
import android.support.annotation.NonNull;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v4.view.ViewCompat;
import android.support.v7.widget.Toolbar;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * ================================================
 * Created by ${chenyuexueer}
 * 时间： 2018/7/7.
 * 说明：状态栏适配工具类
 *
 * 使用一：代码设置
 *      manifest：
 *      样式：
 *
 *      StatusBarColorUtil.setStatusBarColor(this, ContextCompat.getColor(this, R.color.colorAccent));
 *
 * 使用二：toolbar设置
 *      manifest：android:theme="@style/AppTheme.StatusBarColorWithToolbar"
 *      样式：
         <style name="AppTheme.StatusBarColorWithToolbar" parent="Theme.AppCompat.Light.NoActionBar">
         <item name="colorPrimary">@color/statusBarColor</item>
         <item name="colorPrimaryDark">@color/statusBarColorDark</item>
         <item name="colorAccent">@color/statusBarColorLight</item>
         </style>
 * 例如
 *      Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
 *      setSupportActionBar(toolbar);
 *      getSupportActionBar().setTitle(XXX);
 *      StatusBarColorUtil.setStatusBarColor(this, ContextCompat.getColor(this, R.color.colorAccent));
 *
 * 使用三：半透明设置与透明设置
 *          manifest：android:theme="@style/AppTheme.NoActionBar"
 *          样式：
             <style name="AppTheme.NoActionBar" parent="Theme.AppCompat.Light.NoActionBar">
             <item name="colorPrimary">@color/colorPrimary</item>
             <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
             <item name="colorAccent">@color/colorAccent</item>
             </style>
 * 1、全屏无状态栏
 *      manifest：同上
 *      样式：同上
 * ①使用requestWindowFeature(Window.FEATURE_NO_TITLE);
 * ②隐藏ActionBar——getSupportActionBar().hide();
 * 2、使用AppTheme.NoActionBar 样式
 *      manifest：同上
 *      样式：同上
 * 例如
 *      //requestWindowFeature(Window.FEATURE_NO_TITLE);
 *      super.onCreate(savedInstanceState);
 *      setContentView(R.layout.activity_statusbar_translucent);
 *      //getSupportActionBar().hide();
 *      StatusBarColorUtil.translucentStatusBar(this, false);
 *      findViewById(R.id.toggle).setOnClickListener(new View.OnClickListener() {
 *      @Override
 *      public void onClick(View v) {isHide = !isHide;StatusBarColorUtil.translucentStatusBar(this, isHide);}});
 *
 * 使用四：CoordinatorLayout设置
 *      Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
 *      setSupportActionBar(toolbar);
 *      getSupportActionBar().setTitle(XXX);
 *      StatusBarColorUtil.setStatusBarColor(this, ContextCompat.getColor(this, R.color.colorPrimary));
 *      布局：<CoordinatorLayout>
 *                      <AppBarLayout>
 *                          <Toolbar
 *                                  android:layout_height="?attr/actionBarSize"
 *                                  android:background="?attr/colorPrimary"
 *                                  app:layout_scrollFlags="scroll|enterAlways|snap"
 *                                  app:title="Status bar color coordinator layout" >
 *                          </Toolbar>
 *                      <AppBarLayout/>
 *                 <CoordinatorLayout/>
 *
 * 使用五：半透明设置与透明+CoordinatorLayout   设置
 *       Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
 *       setSupportActionBar(toolbar);
 *       getSupportActionBar().setTitle(XXX);
 *       AppBarLayout mAppBarLayout = (AppBarLayout) findViewById(R.id.appbar);
 *       CollapsingToolbarLayout collapsingToolbarLayout = (CollapsingToolbarLayout) findViewById(R.id.collapsing_layout);
 *       collapsingToolbarLayout.setTitle(XXX);
 *       StatusBarColorUtil.setStatusBarColorForCollapsingToolbar(this, mAppBarLayout, collapsingToolbarLayout, toolbar, ContextCompat.getColor(this, R.color.colorPrimary));
 *       布局：<CoordinatorLayout>
 *                      <AppBarLayout>
 *                          <CollapsingToolbarLayout
 *                                  app:contentScrim="@color/colorPrimary"
 *                                  app:expandedTitleMarginEnd="64dp"
 *                                  app:expandedTitleMarginStart="48dp"
 *                                  app:layout_scrollFlags="scroll|exitUntilCollapsed"
 *                                  app:statusBarScrim="@color/colorPrimary">
 *
 *                                  <ImageView
 *                                      android:fitsSystemWindows="true"
 *                                      app:layout_collapseMode="parallax">
 *                                  </ImageView>
 *                                  <Toolbar
 *                                      app:layout_collapseMode="pin"
 *                                      app:popupTheme="@style/ThemeOverlay.AppCompat.Light" >
 *                                   </Toolbar>
 *
 *                          </CollapsingToolbarLayout>
 *                      <AppBarLayout/>
 *                 <CoordinatorLayout/>
 *
 * ================================================
 */
public class StatusBarColorUtil {
    public static void setStatusBarColor(Activity activity, int statusColor) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            StatusBarLollipop.setStatusBarColor(activity, statusColor);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            StatusBarKitKat.setStatusBarColor(activity, statusColor);
        }
    }

    public static void translucentStatusBar(Activity activity) {
        translucentStatusBar(activity, false);
    }

    public static void translucentStatusBar(Activity activity, boolean hideStatusBarBackground) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            StatusBarLollipop.translucentStatusBar(activity, hideStatusBarBackground);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            StatusBarKitKat.translucentStatusBar(activity);
        }
    }

    public static void setStatusBarColorForCollapsingToolbar(@NonNull Activity activity, AppBarLayout appBarLayout, CollapsingToolbarLayout collapsingToolbarLayout,
                                                             Toolbar toolbar, @ColorInt int statusColor) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            StatusBarLollipop.setStatusBarColorForCollapsingToolbar(activity, appBarLayout, collapsingToolbarLayout, toolbar, statusColor);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            StatusBarKitKat.setStatusBarColorForCollapsingToolbar(activity, appBarLayout, collapsingToolbarLayout, toolbar, statusColor);
        }
    }

    public static void setStatusBarLightMode(Activity activity, int color) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            //判断是否为小米或魅族手机，如果是则将状态栏文字改为黑色
            if (MIUISetStatusBarLightMode(activity, true) || FlymeSetStatusBarLightMode(activity, true)) {
                //设置状态栏为指定颜色
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {//5.0
                    activity.getWindow().setStatusBarColor(color);
                } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {//4.4
                    //调用修改状态栏颜色的方法
                    setStatusBarColor(activity, color);
                }
            } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                //如果是6.0以上将状态栏文字改为黑色，并设置状态栏颜色
                activity.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
                activity.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
                activity.getWindow().setStatusBarColor(color);

                //fitsSystemWindow 为 false, 不预留系统栏位置.
                ViewGroup mContentView = activity.getWindow().findViewById(Window.ID_ANDROID_CONTENT);
                View mChildView = mContentView.getChildAt(0);
                if (mChildView != null) {
                    mChildView.setFitsSystemWindows(true);
                    ViewCompat.requestApplyInsets(mChildView);
                }
            }
        }
    }


    public static void setStatusBarLightForCollapsingToolbar(Activity activity, AppBarLayout appBarLayout,
                                                             CollapsingToolbarLayout collapsingToolbarLayout, Toolbar toolbar, int statusBarColor) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            StatusBarLollipop.setStatusBarWhiteForCollapsingToolbar(activity, appBarLayout, collapsingToolbarLayout, toolbar, statusBarColor);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            StatusBarKitKat.setStatusBarWhiteForCollapsingToolbar(activity, appBarLayout, collapsingToolbarLayout, toolbar, statusBarColor);
        }
    }


    /**
     * MIUI的沉浸支持透明白色字体和透明黑色字体
     * https://dev.mi.com/console/doc/detail?pId=1159
     */
    static boolean MIUISetStatusBarLightMode(Activity activity, boolean darkmode) {
        try {
            Class<?> layoutParams = Class.forName("android.view.MiuiWindowManager$LayoutParams");

            Window window = activity.getWindow();
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);

            Class<? extends Window> clazz = activity.getWindow().getClass();
            Field field = layoutParams.getField("EXTRA_FLAG_STATUS_BAR_DARK_MODE");
            int darkModeFlag = field.getInt(layoutParams);
            Method extraFlagField = clazz.getMethod("setExtraFlags", int.class, int.class);
            extraFlagField.invoke(activity.getWindow(), darkmode ? darkModeFlag : 0, darkModeFlag);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 设置状态栏图标为深色和魅族特定的文字风格，Flyme4.0以上
     */
    static boolean FlymeSetStatusBarLightMode(Activity activity, boolean darkmode) {
        try {
            WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
            Field darkFlag = WindowManager.LayoutParams.class
                    .getDeclaredField("MEIZU_FLAG_DARK_STATUS_BAR_ICON");
            Field meizuFlags = WindowManager.LayoutParams.class
                    .getDeclaredField("meizuFlags");
            darkFlag.setAccessible(true);
            meizuFlags.setAccessible(true);
            int bit = darkFlag.getInt(null);
            int value = meizuFlags.getInt(lp);
            if (darkmode) {
                value |= bit;
            } else {
                value &= ~bit;
            }
            meizuFlags.setInt(lp, value);
            activity.getWindow().setAttributes(lp);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    static void setContentTopPadding(Activity activity, int padding) {
        ViewGroup mContentView = activity.getWindow().findViewById(Window.ID_ANDROID_CONTENT);
        mContentView.setPadding(0, padding, 0, 0);
    }

    static int getPxFromDp(Context context, float dp) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, context.getResources().getDisplayMetrics());
    }
}
